# pip install requests
import json

import requests
import hashlib
from urllib.parse import urlparse, parse_qs


def md5_with_salt(url, salt):
    # 解析URL
    parsed_url = urlparse(url)
    # 获取URL中的参数
    params = parse_qs(parsed_url.query)
    # 对参数进行排序
    sorted_params = sorted(params.items())
    # 拼接参数和盐值
    sorted_params_str = ''.join([f'{k}{v}' for k, v in sorted_params]) + salt
    # 计算MD5
    md5 = hashlib.md5()
    md5.update(sorted_params_str.encode('utf-8'))
    return md5.hexdigest()


headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
    'Cookie': 'kg_mid=e5191d7451ee2f21f11a892d8759aa8a; Hm_lvt_aedee6983d4cfc62f509129360d6bb3d=1719466259; kg_dfid=1twWxC42ihMI1zPqPH46ffkh; kg_dfid_collect=d41d8cd98f00b204e9800998ecf8427e; kg_mid_temp=e5191d7451ee2f21f11a892d8759aa8a; Hm_lpvt_aedee6983d4cfc62f509129360d6bb3d=1719536047'
}

list_url = 'https://complexsearch.kugou.com/v2/search/song?callback=callback123&srcappid=2919&clientver=1000&clienttime=1719475869201&mid=e5191d7451ee2f21f11a892d8759aa8a&uuid=e5191d7451ee2f21f11a892d8759aa8a&dfid=1twWxC42ihMI1zPqPH46ffkh&keyword=%E5%A4%A7%E9%B1%BC&page=1&pagesize=30&bitrate=0&isfuzzy=0&inputtype=0&platform=WebFilter&userid=0&iscorrection=1&privilege_filter=0&filter=10&token=&appid=1014&signature=fd6b5c3d99d373f6db0efdd0d0163c5b'

list_res = requests.get(list_url, headers=headers)

list_dic = json.loads(list_res.text[12: -2])
list_dic = list_dic['data']['lists']

for song in list_dic:
    print(f'{song['FileName']}-------{song['FileHash']}-------{song['EMixSongID']}')
    mp3_info_url = f'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash={song["FileHash"]}'
    # mp3_info_url = f'https://wwwapi.kugou.com/play/songinfo?srcappid=2919&clientver=20000&clienttime=1719483355756&mid=e5191d7451ee2f21f11a892d8759aa8a&uuid=e5191d7451ee2f21f11a892d8759aa8a&dfid=1twWxC42ihMI1zPqPH46ffkh&appid=1014&platid=4&encode_album_audio_id={song['EMixSongID']}&token=&userid=0'
    # signature = md5_with_salt(mp3_info_url, 'NVPh5oo715z5DIWAeQlhMDsWXXQV4hwt')
    # mp3_info_url = mp3_info_url + '&signature=' + signature
    song_info_res = requests.get(mp3_info_url, headers=headers)
    song_info_res = json.loads(song_info_res.text)
    song_res = requests.get(song_info_res['data']['play_url'], headers=headers)
    with open(f'{song['FileName']}.mp3', 'wb') as f:
        f.write(song_res.content)
